package com.czl.module_service.viewmodel

import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.TimeUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.binding.command.BindingConsumer
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.PaymentData
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.czl.base.util.ToastHelper
import com.google.gson.JsonArray
import java.util.*

class HousesPaymentDetailViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    val uc = UiChangeEvent()
    var billId : Int? = null
    var bean = ObservableField(PaymentData())
    var status = "" //  >0 支付成功，0 待支付，-1 支付失败，-2 退款中，-3 已退款

    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<PaymentData> = SingleLiveEvent()
        val onPayClickEvent: SingleLiveEvent<String> = SingleLiveEvent()
    }

    val goToPayClick : BindingCommand<Any> = BindingCommand(BindingAction {
        // 同意
        val billIds = JsonArray()
        billIds.add(billId)
        val userId = model.getUserId()
        uc.onPayClickEvent.postValue(
            GsonUtils.toJson(
                mapOf(
                    "billId" to billId.toString(),
                    "payMethod" to "chdZFB",
                    "ownerId" to userId.toString(),
                    "phone" to model.getLoginPhone(),
                    "areaId" to model.getAreaId(),
                    "payAmount" to bean.get()?.payableMoney.toString(),
                    "factRegister" to bean.get()?.payableMoney.toString(),
                    "balaState" to ""
                )
            )
        )
    })

    fun getDetailsByBillId(
        billId : Int? = null
    ) {
        model.getDetailsByBillId(billId!!)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<PaymentData>>(){
                override fun onResult(t: BaseBean<PaymentData>) {
                    if (t.state == 0){
//                        payableDateShortStr.set(t.data?.buildName)
                        uc.loadCompleteEvent.postValue(t.data)
                    } else {
                        uc.loadCompleteEvent.postValue(null)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                    uc.loadCompleteEvent.postValue(null)
                }

            })
    }
}